package top.kaoshanji.r2ch07c;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import top.kaoshanji.r2ch07b.PerformanceMonitor;

import java.lang.reflect.Method;

/**
 * 代码清单-r2ch07c-228页a：一个cglib实例
 * @author kaoshanji
 * ^_^
 * create time 2025/5/7 15:12
 */
public class CglibProxy implements MethodInterceptor {

    // 为一个类创建动态代理对象，该代理对象通过扩展 clazz 实现代理
    public Object getProxy(Class clazz) {
        Enhancer enhancer = new Enhancer();

        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);

        return enhancer.create();
    }

    // 拦截所有目标类方法的调用
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        PerformanceMonitor.begin(o.getClass().getName() + "." + method.getName());

        Object result = methodProxy.invokeSuper(o, objects);

        PerformanceMonitor.end();

        return result;
    }
}
